package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.RandomUtil;
import com.tanhua.autoconfig.template.AipFaceTemplate;
import com.tanhua.autoconfig.template.OssTemplate;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.*;
import com.tanhua.model.domain.User;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.mongo.UserLike;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.InteractiveListVo;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.UserInfoVo;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserInfoService {

    @DubboReference
    private UserInfoApi userInfoApi;

    @Autowired
    private OssTemplate ossTemplate;

    @Autowired
    private AipFaceTemplate aipFaceTemplate;

    @DubboReference
    private UserApi userApi;

    @DubboReference
    private FriendApi friendApi;

    @DubboReference
    private VisitorsApi visitorsApi;

    @DubboReference
    private UserLikeApi userLikeApi;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    public void save(UserInfo userInfo) {
        userInfoApi.save(userInfo);
    }

    //更新用户头像
    public void updateHead(MultipartFile headPhoto, Long id) throws IOException {
        //1、将图片上传到阿里云oss
        String imageUrl = ossTemplate.upload(headPhoto.getOriginalFilename(), headPhoto.getInputStream());
        //2、调用百度云判断是否包含人脸
        boolean detect = aipFaceTemplate.detect(imageUrl);
        //2.1 如果不包含人脸，抛出异常
        if(!detect) {
            throw new BusinessException(ErrorResult.faceError());
        }else{
            //2.2 包含人脸，调用API更新
            UserInfo userInfo = new UserInfo();
            userInfo.setId(id);
            userInfo.setAvatar(imageUrl);
            userInfoApi.update(userInfo);
        }
    }

    //根据id查寻
    public UserInfoVo findById(Long id) {
        UserInfo userInfo = userInfoApi.findById(id);

        UserInfoVo vo = new UserInfoVo();

        BeanUtils.copyProperties(userInfo,vo); //copy同名同类型的属性

        if(userInfo.getAge() != null) {
            vo.setAge(userInfo.getAge().toString());
        }

        return vo;
    }

    //更新
    public void update(UserInfo userInfo) {
        userInfoApi.update(userInfo);
    }


    /*
    * 获取验证码
    *
    * */
    public String findPhone(Long userId) {
        User us = userApi.findById(userId);
        return us.getMobile();
    }

    public User findByPhone(String phone) {
        User user = userApi.findByMobile(phone);
        return user;
    }

    public void updateUser(String phone) {
        Long userId = UserHolder.getUserId();
        User us = userApi.findById(userId);
        us.setMobile(phone);
        userApi.update(us);
    }

    /**
     * 互相喜欢、喜欢、粉丝、谁看过我 - 翻页列表
     *
     * @param page
     * @param pageSize
     * @param type
     * @param nickname
     * @return
     */
    public PageResult friendInteraction(Integer page, Integer pageSize, Integer type, String nickname) {
        switch (type) {
            case 1: //查询互相关注列表
                //查询好友列表，互为好友及为互相喜欢。（小丁说的）
                List<Long> friendIds = friendApi.findFriendsByPage(page, pageSize, UserHolder.getUserId());
                if (CollUtil.isEmpty(friendIds)) {
                    throw new BusinessException(ErrorResult.builder().errMessage("暂无互关好友").build());
                }
                UserInfo userInfo = new UserInfo();
                if (!StringUtils.isEmpty(nickname)) {
                    userInfo.setNickname(nickname);
                }
                Map<Long, UserInfo> userInfoMap = userInfoApi.findRecommendUserInfo(friendIds, userInfo);
                List<InteractiveListVo> listVos = new ArrayList<>();
                for (Long friendId : friendIds) {
                    UserInfo info = userInfoMap.get(friendId);
                    InteractiveListVo vo = new InteractiveListVo();
                    if (info!=null){
                        BeanUtils.copyProperties(info, vo);
                        vo.setMatchRate(RandomUtil.randomInt(30,99));
                        listVos.add(vo);
                    }
                }
                return new PageResult(page, pageSize, 0L, listVos);
            case 2:
                List<Long> youLikeIds = userLikeApi.findMyLike(page, pageSize, UserHolder.getUserId());
                if (CollUtil.isEmpty(youLikeIds)) {
                    throw new BusinessException(ErrorResult.builder().errMessage("暂无互关好友").build());
                }
                UserInfo youLikeInfo = new UserInfo();
                if (!StringUtils.isEmpty(nickname)) {
                    youLikeInfo.setNickname(nickname);
                }
                Map<Long, UserInfo> likeMap = userInfoApi.findRecommendUserInfo(youLikeIds, youLikeInfo);
                List<InteractiveListVo> youLikeVos = new ArrayList<>();
                for (Long friendId : youLikeIds) {
                    UserInfo info = likeMap.get(friendId);
                    InteractiveListVo vo = new InteractiveListVo();
                    if (info!=null){
                        BeanUtils.copyProperties(info, vo);
                        vo.setMatchRate(RandomUtil.randomInt(30,99));
                        youLikeVos.add(vo);
                    }
                }
                return new PageResult(page, pageSize, 0L, youLikeVos);
            case 3:
                //我的粉丝，LikeYou
                List<Long> likeYouIds = userLikeApi.findLikeYou(page, pageSize, UserHolder.getUserId());
                if (CollUtil.isEmpty(likeYouIds)) {
                    throw new BusinessException(ErrorResult.builder().errMessage("暂无粉丝").build());
                }
                UserInfo likeYouInfo = new UserInfo();
                if (!StringUtils.isEmpty(nickname)) {
                    likeYouInfo.setNickname(nickname);
                }
                Map<Long, UserInfo> likeYouMap = userInfoApi.findRecommendUserInfo(likeYouIds, likeYouInfo);
                List<InteractiveListVo> likeYouVos = new ArrayList<>();
                for (Long friendId : likeYouIds) {
                    UserInfo info = likeYouMap.get(friendId);
                    InteractiveListVo vo = new InteractiveListVo();
                    if (info!=null){
                        BeanUtils.copyProperties(info, vo);
                        Boolean result = friendApi.isTwoWayFriend(UserHolder.getUserId(),friendId);
                        vo.setAlreadyLove(result);
                        vo.setMatchRate(RandomUtil.randomInt(30,99));
                        likeYouVos.add(vo);
                    }
                }
                return new PageResult(page, pageSize, 0L, likeYouVos);
            case 4:
                //谁看过我，查看访客表
                List<Long> visitorIds = visitorsApi.findVisitorsByPage(page, pageSize, UserHolder.getUserId());
                if (CollUtil.isEmpty(visitorIds)) {
                    throw new BusinessException(ErrorResult.builder().errMessage("暂无互关好友").build());
                }
                UserInfo visitInfo = new UserInfo();
                if (!StringUtils.isEmpty(nickname)) {
                    visitInfo.setNickname(nickname);
                }
                Map<Long, UserInfo> visitMap = userInfoApi.findRecommendUserInfo(visitorIds, visitInfo);
                List<InteractiveListVo> visitVos = new ArrayList<>();
                for (Long friendId : visitorIds) {
                    UserInfo info = visitMap.get(friendId);
                    InteractiveListVo vo = new InteractiveListVo();
                    if (info!=null){
                        BeanUtils.copyProperties(info, vo);
                        vo.setAlreadyLove(false);
                        vo.setMatchRate(RandomUtil.randomInt(30,99));
                        visitVos.add(vo);
                    }
                }
                return new PageResult(page, pageSize, 0L, visitVos);
        }
        return new PageResult();
    }


    public void fanLike(Long uid) {
        UserLike like = userLikeApi.hasLove(UserHolder.getUserId(), uid);
        if (like ==null){
            UserLike userLike = new UserLike();
            userLike.setUserId(UserHolder.getUserId());
            userLike.setLikeUserId(uid);
            userLike.setUpdated(System.currentTimeMillis());
            userLike.setCreated(System.currentTimeMillis());
            userLike.setIsLike(true);
            //添加到喜欢，即双向喜欢，
            userLikeApi.saveLoveStatus(userLike);
        }else {
            UserLike userLike = new UserLike();
            userLike.setIsLike(true);
            userLikeApi.updateLoveStatus(userLike);
        }
        //双向喜欢，即为好友，添加好友关系
        friendApi.addFriendContacts(UserHolder.getUserId(),uid);
    }

    //取消喜欢--将用户喜欢表中的当前用户喜欢当前粉丝（要取消人）
    public void cancelLike(Long uid) {
        Boolean twoWayFriend = friendApi.isTwoWayFriend(UserHolder.getUserId(), uid);
        if (twoWayFriend){
            friendApi.deleteFriend(UserHolder.getUserId(),uid);
        }
        UserLike userLike = userLikeApi.findOne(UserHolder.getUserId(),uid);
        userLike.setIsLike(false);
        userLikeApi.updateLoveStatus(userLike);
    }

    /**
     * 发送验证码
     */
    public void sendVerificationCode() {
        String phone = UserHolder.getMobile();
        //给指定手机号发送验证码
        //smsTemplate.sendSms(phone,"123456");
        //并将验证码保存到数据库
        redisTemplate.opsForValue().set(Constants.SMS_CODE + phone, "123456");
    }

    /**
     * 检验验证码
     *
     * @param verificationCode
     * @return
     */
    public Map checkVerificationCode(String verificationCode) {
        String code = redisTemplate.opsForValue().get(Constants.SMS_CODE + UserHolder.getMobile());
        if (StringUtils.isEmpty(verificationCode) || StringUtils.isEmpty(code) || !verificationCode.equals(code)) {
            throw new BusinessException(ErrorResult.loginError());
        }
        //校验成功,清除缓存
        Boolean delete = redisTemplate.delete(Constants.SMS_CODE + UserHolder.getMobile());
        Map map = new HashMap();
        map.put("verification", delete);
        return map;
    }

    //保存用户新的手机号
    public void saveNewPhone(String newPhone) {
        User byPhone = userApi.findByMobile(newPhone);
        if (byPhone != null) {
            throw new BusinessException(ErrorResult.builder().errMessage("当前手机号已被注册，请检查").build());
        }
        User user = userApi.findByMobile(UserHolder.getMobile());
        user.setMobile(newPhone);
        userApi.update(user);
        //删除token令牌?不用 ，当前继续使用，等下次登录更换。。。
    }

}
